import { PrismaService } from '@/modules/prisma/prisma.service';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Inject } from '@nestjs/common';
import { Cache } from 'cache-manager';
import {
  BadRequestException,
  ConflictException,
  Injectable,
  NotFoundException,
} from '@nestjs/common';
import { OssService } from './oss.service';
import { v4 as uuid } from 'uuid';
import { completeUploadDto } from './transfer.dto';

@Injectable()
export class TransferService {
  constructor(
    private prisma: PrismaService,
    private readonly OssService: OssService,
    @Inject(CACHE_MANAGER) private cacheManager: Cache,
  ) {}

  async preUpload(userId: number, filename: string, filetype: string) {
    const id = uuid();
    const ossPath = `${filetype}/${userId}/${id}_${filename}`;

    const url = await this.OssService.generateUploadUrl(ossPath);
    return { fileId: id, uploadUrl: url, ossPath: ossPath };
  }
  async viewFile(id: string) {
    const file = await this.prisma.file.findUnique({
      where: { id },
      select: {
        ossPath: true,
      },
    });
    if (!file) {
      throw new Error(`File with ID ${id} not found`);
    }

    // 2. 处理 ossPath 为 null 的情况
    if (file.ossPath === null) {
      throw new Error(`OSS path is missing for file ${id}`);
    }
    const url = await this.OssService.generateAccessUrl(file.ossPath);
    return { fileId: id, viewUrl: url };
  }

  async completeUpload(body: completeUploadDto, userId: number) {
    const { customAlphabet } = await import('nanoid');
    const generateDocumentId = customAlphabet(
      'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
      20,
    );
    const shortId = generateDocumentId();

    // 处理文件名重复
    let fileName = body.name;
    let counter = 1;

    // 分离文件名和扩展名
    const lastDotIndex = fileName.lastIndexOf('.');
    let baseName = fileName;
    let extension = '';
    if (lastDotIndex !== -1) {
      baseName = fileName.substring(0, lastDotIndex);
      extension = fileName.substring(lastDotIndex);
    }

    // 检查基础名称是否已有编号
    const baseMatch = baseName.match(/^(.*?)\s\((\d+)\)$/);
    if (baseMatch) {
      baseName = baseMatch[1];
      counter = parseInt(baseMatch[2], 10) + 1;
    }

    // 循环检查直到找到可用文件名
    while (true) {
      const existing = await this.prisma.file.findFirst({
        where: {
          parentId: body.folderId,
          name: fileName,
        },
      });

      if (!existing) break;

      // 生成新文件名
      fileName = `${baseName} (${counter})${extension}`;
      counter++;
    }

    //需要核实一下上传的对不对！！！

    await this.prisma.file.create({
      data: {
        id: body.id,
        name: fileName,
        type: body.filetype,
        parentId: body.folderId,
        shortId: shortId,
        ossPath: body.ossPath,
        status: 'active',
        creatId: userId,
        groupId: body.groupId!,
      },
    });
    return 'ok';
  }
}
